<!--
 	* @author  dumeng
-->
<template>
  <div class="question-tiankong">
    <el-form
        ref="tiankongform"
        :model="baseform"
        :rules="baserules"
        class="dataForm nomt"
        label-position="right"
        label-width="100px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="题干" prop="stem">
            <el-input
                v-model.trim="baseform.stem"
                :rows="2"
                :disabled="disabled"
                type="textarea"
                placeholder="题干这里填写题目描述"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
              v-for="(item, index) in baseform.answer"
              :key="index"
              :label="`第${toChinesNum(index+1)}空答案`"
              required
              class="options"
          >
            <el-input
                v-model.trim="baseform.answer[index]"
                :disabled="$parent.$route.name !== 'exercisesManage' && !canSelectRa"
                placeholder="请输入答案"
            />
            <template v-if="canSelectRa">
              <span class="option-rightasnwer">原正确答案</span>
              <el-input v-model.trim="rightA[index]" disabled style="margin-right: 0;"/>
            </template>
            <span v-if="!disabled" @click.prevent="removeAnswer(index)" class="remove-option">
              <i class="el-icon-delete"/>
            </span>
          </el-form-item>
        </el-col>
        <el-col v-if="!disabled" :span="24">
          <el-button icon="el-icon-circle-plus" class="add-optiopn" @click="addAnswer">增加答案</el-button>
        </el-col>
        <el-col v-if="!disabled" :span="24">
          <el-checkbox class="order-fixed" v-model="orderFixed">填空题答案不分顺序</el-checkbox>
        </el-col>
        <el-col :span="24" class="tip">
          <div>说明文字：（1）如果填空题有多个空，每个空的答案单独填写。举例：中国共产党第二次代表大会与（ ）年召开，召开地址是（ ）。第一空答案：1922 第二空答案：上海。</div>
          <div>(2）如果一个空的答案可能有多种写法。多种写法用“|”隔开。举例：上面的第一空的答案写1922或一九二二都是正确的。第一空答案可设为：1922|一九二二。</div>
          <div>
            (3)举例：被称作“前四史”的史书是（）、（）、（）、（）。对于这样的填空题，答案顺序是可变的。需要将该题设置为“填空题答案不分顺序”。第一空答案：史记。第二空答案：汉书。第三空答案：后汉书。第四空答案：三国志。
          </div>
        </el-col>
        <el-col v-if="!disabled" :span="24">
          <el-form-item label="排序" prop="sort">
            <el-input v-model.trim="baseform.sort" placeholder="请输入排序号"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="试题解析">
            <el-input
                v-model.trim="baseform.questionAnalysis"
                :rows="2"
                :disabled="disabled"
                type="textarea"
                placeholder="添加试题解析，便于更好的理解答案"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { specialText, number } from '@/utils/validate'

export default {
  name: "Tiankong",
  props: {
    type: {
      type: String,
      default: '40'
    },
    getData: {
      type: Object,
      default: () => {
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    toggleRightAnswer: { // 是否可以切换正确答案
      type: Boolean,
      default: false
    }
  },
  watch: {
    toggleRightAnswer(val) {
      this.canSelectRa = val
    }
  },
  data() {
    return {
      baseform: {
        stem: '',
        answer: [''],
        sort: '',
        questionAnalysis: ''
      },
      baserules: {
        stem: [
          {required: true, message: '请输入题干', trigger: 'blur'}
        ],
        opts: [
          {required: true, message: '请输入备选答案', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序号', trigger: 'blur'},
          {validator: number, trigger: 'blur'}
        ],
      },
      orderFixed: false,
      canSelectRa: false,
      rightA: []
    }
  },
  methods: {
    /**
     * 数字转中文
     */
    toChinesNum(num) {
      let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
      let unit = ["", "十", "百", "千", "万"];
      num = parseInt(num);
      let getWan = (temp) => {
        let strArr = temp.toString().split("").reverse();
        let newNum = "";
        for (var i = 0; i < strArr.length; i++) {
          newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
        }
        return newNum;
      }
      let overWan = Math.floor(num / 10000);
      let noWan = num % 10000;
      if (noWan.toString().length < 4) {
        noWan = "0" + noWan;
      }
      return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
    },
    /**
     * 删除指定选项
     * @param i
     */
    removeAnswer(i) {
      this.baseform.answer.splice(i, 1)
    },
    /**
     * 添加选项
     */
    addAnswer() {
      this.baseform.answer.push('')
    },
    getPostData() {
      let params = ''
      if (!this.baseform.answer.some(item => item)) {
        this.$message({
          message: '请填写答案！',
          type: 'warning'
        })
        return false
      }
      this.$refs.tiankongform.validate(valid => {
        if (valid) {
          let answer = {
            type: this.type,
            flags: this.orderFixed ? ['填空题答案不分顺序'] : [],
            answers: this.baseform.answer.filter(s => {
              return s && s.trim()
            })
          }
          params = {
            answer: JSON.stringify(answer),
            stem: this.baseform.stem,
            sort: this.baseform.sort,
            questionNumber: this.baseform.answer.length,
            questionAnalysis: this.baseform.questionAnalysis
          }
        }
      })
      return params
    }
  },
  created() {
    if (this.getData && this.getData.id) {
      try {
        if (this.getData.question && this.getData.dealType ) {//错题回显返回的数据
          this.$set(this.baseform, 'stem',this.getData.question.stem)
          this.$set(this.baseform, 'sort', this.getData.question.sort)
          this.$set(this.baseform, 'questionAnalysis', this.getData.question.questionAnalysis)
          let answer = this.getData.dealType == 10 ? JSON.parse(this.getData.question.answer) : JSON.parse(this.getData.answer)
          this.$set(this.baseform, 'answer', answer.answers)
          this.$set(this, 'orderFixed', answer.flags && answer.flags.length > 0)
          this.$set(this, 'rightA', JSON.parse(this.getData.question.answer).answers)
          this.canSelectRa = this.getData.dealType == 10 ? false : true
        } else {
          let answer = JSON.parse(this.getData.answer)
          this.$set(this.baseform, 'stem', this.getData.stem)
          this.$set(this.baseform, 'sort', this.getData.sort)
          this.$set(this.baseform, 'questionAnalysis', this.getData.questionAnalysis)
          this.$set(this.baseform, 'answer', answer.answers)
          this.$set(this, 'orderFixed', answer.flags && answer.flags.length > 0)
          this.$set(this, 'rightA', answer.answers)
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '参数异常，请重试!',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    }
  }
}
</script>

<style lang="scss">
.question-tiankong {
  .el-form-item.fixed .el-form-item__content {
    display: flex;
    align-items: center;

    .el-input {
      width: auto;
    }

    .score-tip {
      margin-left: 20px;
      color: red;
    }
  }

  .el-radio-group {
    width: 100%;
  }

  .options .el-form-item__content {
    display: flex;
    align-items: center;

    .el-input {
      width: 100%;
      margin-right: 20px;
    }
  }

  .option-rightasnwer {
    display: inline-block;
    flex-shrink: 0;
    font-size: 14px;
    color: green;
    margin-right: 10px;
  }

  .order-fixed {
    margin: 10px 0;
    padding-left: 100px;
  }

  .remove-option {
    cursor: pointer;
  }

  .add-optiopn {
    margin-left: 100px;
  }

  .tip {
    padding-left: 100px;
    padding-bottom: 10px;
    color: red;

    div {
      margin-top: 10px;
    }
  }
}
</style>